<template>
  <view>

    <view class="userTimeWrapper">
      <!-- 日历组件 -->
      <view class="calendarWrapper">
        <vant-calendar type="range" :formatter="formatter" :show-title="false" :show-subtitle="false"
                       :poppable="false" :show-confirm="false" :default-date="defaultDate" color="#1989fa"
                       :style="{ height: '200px' }" @select="calendarSelect" :max-date="maxDate"></vant-calendar>
      </view>
      <!-- 时间组件 -->
      <view class="datetimeWrapper">
        <view class="timeTabbar">
          <text>取车时间</text>
          <text>还车时间</text>
        </view>
        <vant-picker :columns="columns" item-height="36" @change="minutesChange">
        </vant-picker>
      </view>
    </view>


    <!-- 底部按钮 -->
    <view class="bottomWrapper">
      <view class="btn" @tap="confimTime">确定</view>
    </view>
	
	<u-modal :show="show" title="提示" :content='alertContent' @confirm="show=false" @close="show=false" confirmText="知道了"></u-modal>
  </view>
</template>

<script>
import {
  storeInfoList,
  validRntalTime
} from '@/api/home-api.js'

const moment = require('@/utils/moment.js');
const formatter = (day) => {
  if (day.type === 'start') {
    day.bottomInfo = '取车';
  } else if (day.type === 'end') {
    day.bottomInfo = '还车';
  }
  return day;
};
export default {
  data() {
    return {
      formatter,
      takeDate: '',
      takeTime: '',
      returnDate: '',
      returnTime: '',
      takeDefaultIndex: 0,
      returnDefaultIndex: 0,
      columns: [],

      takeStoreInfo: {},
      returnStoreInfo: {},
	  show:false,
	  alertContent:'',
	  maxDate:moment().add(6, 'months').valueOf(),
	  // maxDate:moment().add(0, 'days').valueOf(),
    }
  },

  onLoad() {
    console.log(this.startTime, this.endTime);
    this.takeDate = moment(this.startTime).format('YYYY-MM-DD');
    this.returnDate = moment(this.endTime).format('YYYY-MM-DD');
    this.getStoreInfo();
  },
  computed: {
    businessNo() {
      return this.$store.state.order.businessNo;
    },
    tenantId() {
      return this.$store.state.user.tenantId;
    },
    startTime() {
      return this.$store.state.order.startTime;
    },
    endTime() {
      return this.$store.state.order.endTime;
    },
    //下单延时时间
    delayTime() {
      return this.$store.state.initData.initData.delayTime;
    },
    //是否允许营业时间范围外下单 1.允许 2不允许
    outOfTime() {
      return this.$store.state.initData.initData.outOfTime;
    },

    defaultDate() {
      let sDate = moment(this.startTime).valueOf();
      let eDate = moment(this.endTime).valueOf();
      var dates = [sDate, eDate];
      return dates;
    },
    startMin() {
      const delayTime = this.delayTime;
      let minutes = moment().minutes();
      var currentTime;
      var minutesStr = "";
      if (minutes > 30) { //如果大于30->按整点取值
        currentTime = moment().add(delayTime + 1, "hours").format("HH") + ":00"
      } else { //如果不足30分钟->按30分钟取值
        currentTime = moment().add(delayTime, "hours").format("HH") + ":30"
      }
      let todayYMD = moment().format('YYYY-MM-DD');
      let currentFormatTime = todayYMD + ' ' + currentTime;
      const businessEndFormatTime = todayYMD + ' ' + this.takeStoreInfo.businessEndTime;
      // 是否在营业时间之后
      const isEndTimeAfter = moment(currentFormatTime).isAfter(businessEndFormatTime);
      let startMin = moment().valueOf();
      if (isEndTimeAfter) {
        startMin = moment().add(1, 'days').valueOf();
      }
      return startMin;
    }
  },
  methods: {
    //获取门店信息
    getStoreInfo() {
      uni.showLoading({
        title: '加载中...'
      })
      //获取取车门店信息
      storeInfoList({
        tenantId: this.tenantId,
        storeId: this.$store.state.user.takeStoreId,
        lat: this.$store.state.user.takeCarLat,
        lon: this.$store.state.user.takeCarLng,
        bizType: this.businessNo
      }).then(res => {
        uni.hideLoading();
        this.takeStoreInfo = res.data;
		const advanceAppointmentDays = this.takeStoreInfo.advanceAppointmentDays;
		if(advanceAppointmentDays >= 0){
			this.maxDate = moment().add(advanceAppointmentDays, 'days').valueOf();
		}
		
      });

      //获取还车门店信息
      storeInfoList({
        tenantId: this.tenantId,
        storeId: this.$store.state.user.returnStoreId,
        lat: this.$store.state.user.returnCarLat,
        lon: this.$store.state.user.returnCarLng,
        bizType: this.businessNo
      }).then(res => {
        uni.hideLoading();
        this.returnStoreInfo = res.data;
      });
      // console.log(this.columns);
      setTimeout(() => {
        this.setOrderTime();
      }, 1000)

    },

    setOrderTime() {
      let delayTime = this.delayTime;
      let minutes = moment().minutes();
      var currentTime;
      var minutesStr = "";
      if (minutes > 30) { //如果大于30->按整点取值
        currentTime = moment().add(delayTime + 1, "hours").format("HH") + ":00"
      } else { //如果不足30分钟->按30分钟取值
        currentTime = moment().add(delayTime, "hours").format("HH") + ":30"
      }

      //判断取车日期是否是今天
      const result = moment(this.takeDate).isSame(moment(), "day");
      if (result) {//是今天->时间范围只能取当前时间两小时后的时间

        let takeCarMinutes = [];
        if (this.outOfTime === 1) {//允许营业时间范围外下单;
           takeCarMinutes = this.getTimeRange(currentTime, '23:30', 30, 1);
        }else  {
          const delayAfterTimeForamt = moment().format('YYYY-MM-DD') + ' ' + currentTime;
          const businessStartTimeFormat = moment().format('YYYY-MM-DD') + ' ' + this.takeStoreInfo.businessStartTime;
          const isStartTimeBefore = moment(delayAfterTimeForamt).isBefore(businessStartTimeFormat);
          let resultStartTime = '';
          if (isStartTimeBefore) {
            resultStartTime = this.takeStoreInfo.businessStartTime;
          } else {
            resultStartTime = currentTime;
          }
          takeCarMinutes = this.getTimeRange(resultStartTime, this.takeStoreInfo.businessEndTime, 30, 1);
        }

        this.columns.push({
          values: takeCarMinutes,
          defaultIndex: this.takeDefaultIndex,
        })
      } else {//不是今天
        let takeCarMinutes = [];
        if (this.outOfTime === 1) {
           takeCarMinutes = this.getTimeRange('00:00', '23:00', 30, 1);
        }else  {
           takeCarMinutes = this.getTimeRange(this.takeStoreInfo.businessStartTime, this.takeStoreInfo.businessEndTime, 30, 1);
        }

        this.columns.push({
          values: takeCarMinutes,
          defaultIndex: this.takeDefaultIndex,
        })
      }

      let returnCarMinutes = [];
      if (this.outOfTime == 1) {
        returnCarMinutes = this.getTimeRange('00:00', '23:30', 30, 2);
      }else  {
        returnCarMinutes = this.getTimeRange(this.returnStoreInfo.businessStartTime, this.returnStoreInfo.businessEndTime, 30, 2);
      }

      this.columns.push({
        values: returnCarMinutes,
        defaultIndex: this.returnDefaultIndex,
      })


    },

    //选中日历
    calendarSelect(value) {
      let detail = value.detail;
      let takeDate = detail[0];
      let returnDate = detail[1];

      if (takeDate) {
        this.takeDate = moment(takeDate).format('YYYY-MM-DD');
        this.columns = [];
        this.setOrderTime();
      }

      if (returnDate) {
        this.returnDate = moment(returnDate).format('YYYY-MM-DD');

      } else {
        this.returnDate = null;
      }
    },
    //选中时间
    minutesChange(data) {
      var times = data.detail.value;
      this.takeTime = times[0];
      this.returnTime = times[1];
    },

    //根据开始,结束,时间间隔获取时分时间列表
    getTimeRange(startT, endT, interval, type) {
      let starTime = moment(startT, "HH:mm");
      let endTime = moment(endT, "HH:mm");
      let diff = endTime.diff(starTime, "minutes");
      let num = Math.ceil(diff / interval);
      var segs = []
      for (let i = 0; i <= num; i++) {
        let timeFrom = starTime.clone().add((i) * interval, "minutes");
        let timeStr = timeFrom.format("HH:mm");
        if (type == 1) { //取车
          const time = moment(this.startTime).format("HH:mm");
          if (timeStr == time) {
            this.takeDefaultIndex = i;
            this.takeTime = time;
          }
        } else { //还车
          const time = moment(this.endTime).format("HH:mm");
          if (timeStr == time) {
            this.returnDefaultIndex = i;
            this.returnTime = time;
          }
        }
        segs.push(timeStr);
      }
      return segs;
    },
    confimTime() {
      if (!this.$u.test.isEmpty(this.returnDate)) {
        const startTime = this.takeDate + ' ' + this.takeTime + ':00';
        const endTime = this.returnDate + ' ' + this.returnTime + ':00';
        console.log(startTime, endTime);
		validRntalTime({
			takeStoreId : this.$store.state.user.takeStoreId,
			rentalStartTime : startTime,
			rentalEndTime : endTime 
		}).then(res=>{
			if(res.code == 200){
				this.$store.commit('order/saveStartTime', startTime);
				this.$store.commit('order/saveEndTime', endTime);
				uni.$emit('changeTime');
				uni.navigateBack({})
			}else if(res.code == 505) {
				this.alertContent = res.msg;
				this.show = true;
			}
		})
		
      } else {
        uni.$u.toast('请选择还车日期');
      }
    }

  },

}
</script>

<style lang="scss" scoped>
.userTimeWrapper {
  padding-bottom: 100upx;
}


.timeWrapper {
  padding: 20upx 0;
  display: flex;
  justify-content: space-around;
  align-items: center;

  .timeContent {
    display: flex;
    flex-direction: column;

    .date {
      color: $text-color-33;
      font-size: 30upx;
      font-weight: bold;
    }

    .time {
      color: $text-color-66;
      font-size: 24upx;
    }
  }

  .duration {
    color: $text-color-66;
    font-size: 26upx;
  }

}

.calendarWrapper {
  // height: 700upx;
  height: 60%;

}

.datetimeWrapper {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 88rpx;
  height: 400upx;
  // height: 30%;
  background-color: $bg-white-color;
  box-shadow: 0 -2px 5px #F5F5F5;
  overflow: hidden;

  .timeTabbar {
    height: 80upx;
    font-size: 30upx;
    color: $text-color-33;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
}

.bottomWrapper {
  background-color: $bg-white-color;
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;

  .btn {
    background: linear-gradient(to right, #32ace9 0%, #176cfb 100%);
    height: 88upx;
    line-height: 88upx;
    margin: 20upx;
    color: $text-color-ff;
    font-size: 30upx;
    font-weight: bold;
    text-align: center;
    border-radius: 12upx;
  }

}
</style>
